package com.starrin.trashtalk;

import com.starrin.trashtalk.dao.PlayerDAOImpl;
import com.starrin.trashtalk.model.Player;
import com.starrin.trashtalk.util.FacesMessageUtil;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;

@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {

    private String username;
    private String password;
    private boolean loggedIn;
    private String from;
    private Player loggedInPlayer;

    @ManagedProperty(value = "#{navigationBean}")
    private NavigationBean navigationBean;

    public String doLogin() {
        // Get every user from our sample database :)

        Player player = new PlayerDAOImpl().findPlayer(username);

        if (player != null && player.getPassword().equals(password)) {
            // Successful login
            loggedIn = true;
            loggedInPlayer = player;

            if(from != null && !from.equals("")) {
                String viewId = from + "&faces-redirect=true";
                from = null;
                return viewId;
            }
            return navigationBean.redirectToWelcome();
        }

        // Set login ERROR
        FacesMessageUtil.addError("Invalid username or password");

        // To to login page
        return null;
        //return navigationBean.toLogin();
    }

    /**
     * Logout operation.
     *
     * @return
     */
    public String doLogout() {
        // Set the paremeter indicating that user is logged in to false
        loggedIn = false;
        // Set logout message
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        FacesMessageUtil.addInfo("Logout successful!");
        return navigationBean.toLogin();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isLoggedIn() {
        return loggedIn;
    }

    public void setLoggedIn(boolean loggedIn) {
        this.loggedIn = loggedIn;
    }

    public NavigationBean getNavigationBean() {
        return navigationBean;
    }

    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }


    public Player getLoggedInPlayer() {
        return loggedInPlayer;
    }

    public void setLoggedInPlayer(Player loggedInPlayer) {
        this.loggedInPlayer = loggedInPlayer;
    }
}


